package com.cn.shuangzi.ad.custom;

import android.app.Activity;
import android.content.Context;
import android.view.View;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.banner.MediationCustomBannerLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.ThreadUtils;
import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.comm.constants.BiddingLossReason;
import com.qq.e.comm.util.AdError;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * YLH Banner自定义Adapter
 */
public class YlhCustomerBanner extends MediationCustomBannerLoader {


    private UnifiedBannerView mUnifiedBannerView;
    private int price;

    @Override
    public View getAdView() {
        return mUnifiedBannerView;
    }

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig mediationCustomServiceConfig) {
        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                if (context instanceof Activity) {
                    mUnifiedBannerView = new UnifiedBannerView((Activity) context, mediationCustomServiceConfig.getADNNetworkSlotId(),
                            new UnifiedBannerADListener() {
                                @Override
                                public void onNoAD(AdError adError) {
                                    YlhErrorInfo ylhErrorInfo;
                                    if (adError != null) {
                                        ylhErrorInfo = new YlhErrorInfo(BiddingLossReason.NO_AD);
                                        ADUtil.logError("Banner onNoAD errorCode = " + adError.getErrorCode() + " errorMessage = " + adError.getErrorMsg());
                                        callLoadFail(adError.getErrorCode(), adError.getErrorMsg());
                                    } else {
                                        ylhErrorInfo = new YlhErrorInfo(BiddingLossReason.NO_AD);
                                        callLoadFail(ADConst.LOAD_ERROR, "no ad");
                                    }
                                    ADManager.getInstance().setBannerYlhErrorInfo(ylhErrorInfo);
                                }

                                @Override
                                public void onADReceive() {
                                    if (isBidding()) {//bidding类型广告
                                        double ecpm = mUnifiedBannerView.getECPM();//当无权限调用该接口时，SDK会返回错误码-1
                                        if (ecpm < 0) {
                                            ecpm = 0;
                                        }
                                        price = (int) ecpm;

                                        ADManager.getInstance().setBannerYlhErrorInfo(new YlhErrorInfo(BiddingLossReason.LOW_PRICE));
                                        ADUtil.logError("优量汇ecpm:" + ecpm);
                                        callLoadSuccess(ecpm);
                                    } else {//普通类型广告
                                        callLoadSuccess();
                                    }
                                }

                                @Override
                                public void onADExposure() {
                                    if (mUnifiedBannerView != null && price > 0) {
                                        mUnifiedBannerView.sendWinNotification(price);
                                    }
                                    callBannerAdShow();
                                }

                                @Override
                                public void onADClosed() {
                                    callBannerAdClosed();
                                }

                                @Override
                                public void onADClicked() {
                                    callBannerAdClick();
                                }

                                @Override
                                public void onADLeftApplication() {
                                }
                            });
                    mUnifiedBannerView.setRefresh(0); // 设置0表示不轮播，m统一处理了轮播无需设置
                    mUnifiedBannerView.loadAD();
                    ADManager.getInstance().setYlhBannerAd(mUnifiedBannerView);
                } else {
                    callLoadFail(ADConst.LOAD_ERROR, "context is not Activity");
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<MediationConstant.AdIsReadyStatus> future = ThreadUtils.runOnThreadPool(new Callable<MediationConstant.AdIsReadyStatus>() {
            @Override
            public MediationConstant.AdIsReadyStatus call() throws Exception {
                if (mUnifiedBannerView != null && mUnifiedBannerView.isValid()) {
                    return MediationConstant.AdIsReadyStatus.AD_IS_READY;
                } else {
                    return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
                }
            }
        });
        try {
            MediationConstant.AdIsReadyStatus result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null) {
                return result;
            } else {
                return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ADUtil.logError("=====Banner销毁了=====");
        ADManager.getInstance().setYlhBannerAd(null);
        /**
         * 在子线程中进行广告销毁
         */
//        try {
//            ThreadUtils.runOnThreadPool(new Runnable() {
//                @Override
//                public void run() {
        try {
            if (mUnifiedBannerView != null) {
                mUnifiedBannerView.destroy();
                mUnifiedBannerView = null;
            }
        } catch (Exception exception) {
            ADUtil.logError("销毁异常：" + exception);
            exception.printStackTrace();
        }
//                }
//            });
//        } catch (Exception exception) {
//            exception.printStackTrace();
//            ADUtil.logError("销毁异常：" + exception);
//        }
    }

    /**
     * 是否是Bidding广告
     *
     * @return
     */
    public boolean isBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }
}
